package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.dubbo.mappers.UserInfoMapper;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.vo.SimilarYouVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: tanhua
 * @description:
 * @author: MR.peng
 * @create: 2022-03-08 16:18
 **/
@DubboService
public class UserInfoApiImpl  implements UserInfoApi {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public void save(UserInfo userInfo) {
        userInfoMapper.insert(userInfo);
    }

    //根据id更新
    @Override
    public void update(UserInfo userInfo) {
        userInfoMapper.updateById(userInfo);
    }

    //根据id查询用户信息
    @Override
    public UserInfo findUser(Long userId) {
        UserInfo userInfo =  userInfoMapper.selectById(userId);
        return userInfo;
    }

    //根据用户id集合，查询用户
    @Override
    public Map<Long, UserInfo> findByIds(List<Long> userIds) {
        if(CollUtil.isEmpty(userIds)){
            return null;
        }

        //1.根据多个用户id，查询用户list列表
        QueryWrapper<UserInfo> qw = new QueryWrapper<>();
        qw.in("id",userIds);
        List<UserInfo> userInfos = userInfoMapper.selectList(qw);
        //2.转化成Map集合
        Map<Long,UserInfo> map = new HashMap<>();
        for (UserInfo info : userInfos) {
            map.put(info.getId(),info);
        }
        return map;
    }


    //分页查询所有
    @Override
    public IPage findAll(Integer page, Integer pagesize) {
        //分页参数对象
        Page<UserInfo> pageParam = new Page(page,pagesize);
        return userInfoMapper.selectPage(pageParam,null);//分页参数对象  查询条件
    }
    //通过userIds进行查找用户信息
    @Override
    public List<SimilarYouVo> findByIdsVo(List<Long> userIds, Long id) {
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.in("id",userIds);
        wrapper.ne("id",id);
        List<UserInfo> userInfos = userInfoMapper.selectList(wrapper);
        List<SimilarYouVo> vos = new ArrayList<>();
        for (UserInfo userInfo : userInfos) {
            SimilarYouVo vo = SimilarYouVo.inint(userInfo);
            vos.add(vo);
        }
        return vos;
    }
}
